<template>
  <view class="form-box">
    <!--<nui-step :step="2"></nui-step>-->
    <nui-step :step="stepType"></nui-step>
    <u-form :model="form" ref="uForm">
      <u-form-item :label-position="labelPosition" label="身份证（人像面）" prop="idCardBadgeImages" required>
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          :file-list="idCardBadgeImagesFileList"
          @on-choose-complete="idCardBadgeImagesCallback"
        ></u-upload>
      </u-form-item>
      <text class="to-popup" @click="onChangePopup('idCardBadgeImages')">查看示例说明</text>
      <u-form-item :label-position="labelPosition" label="身份证（国徽面）" prop="idCardPortraitImages" required>
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          :file-list="idCardPortraitImagesFileList"
          @on-choose-complete="idCardPortraitImagesCallback"
        ></u-upload>
      </u-form-item>
      <u-form-item :label-position="labelPosition" label="手持身份证照片（仅限于入职使用）" prop="holdIdCardImages" required>
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          @on-choose-complete="holdIdCardImagesCallback"
        ></u-upload>
      </u-form-item>
      <text class="to-popup" @click="onChangePopup('holdIdCardImages')">查看示例说明</text>
      <u-form-item :label-position="labelPosition" label="工资银行卡照片（正面）" prop="backupBankCardNo" required>
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          @on-choose-complete="backupBankCardNoCallback"
        ></u-upload>
      </u-form-item>
      <text class="to-popup" @click="onChangePopup('backupBankCardNo')">查看示例说明</text>
      <!-- <u-form-item label="工资卡开户银行" :label-position="labelPosition" prop="bank_name" required
        ><u-input
          v-model="form.bank_name"
          type="select"
          :select-open="actionNameShow"
          @click="actionNameShow = true"
          placeholder="请选择工资卡开户银行"
      /></u-form-item>
      <u-form-item label="工资卡开户银行卡号" :label-position="labelPosition" prop="bank_cardno" required
        ><u-input v-model="form.bank_cardno" placeholder="请输入工资卡开户银行卡号" @blur="vailCard"
      /></u-form-item>
      <u-form-item label="工资卡开户行支行" :label-position="labelPosition" prop="bank_shop" required
        ><u-input v-model="form.bank_shop" placeholder="请输入工资卡开户行支行"
      /></u-form-item>
      <text class="tips"
        >示例：招商银行广州分行科技园支行 。
        如不清楚开户行支行名称信息，请咨询对应的银行获取，或登录手机银行APP查询。</text
      > -->
      <u-form-item
        :label-position="labelPosition"
        label="学生证明材料"
        prop="studentCertificate"
        v-if="userInfo.isStudent == 0"
        :required="reqIsStudent"
      >
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          @on-choose-complete="studentCertificateCallback"
        ></u-upload>
      </u-form-item>
      <u-form-item label="备注1" :label-position="labelPosition" prop="remark1"
        ><u-input v-model="form.remark1" placeholder="请输入备注1"
      /></u-form-item>
      <u-form-item label="备注2" :label-position="labelPosition" prop="remark2"
        ><u-input v-model="form.remark2" placeholder="请输入备注2"
      /></u-form-item>
      <u-form-item label="备注3" :label-position="labelPosition" prop="remark3"
        ><u-input v-model="form.remark3" placeholder="请输入备注3"
      /></u-form-item>
      <!-- <u-form-item :label-position="labelPosition" label="身份证扫描件" prop="idCardScanning" required>
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          @on-choose-complete="idCardScanningCallback"
        ></u-upload>
      </u-form-item>
      <u-form-item :label-position="labelPosition" label="身份证扫描件备用选项" prop="idCardScanningBak">
        <u-upload
          width="160"
          height="160"
          max-count="1"
          :auto-upload="false"
          @on-choose-complete="idCardScanningBakCallback"
        ></u-upload>
      </u-form-item> -->
    </u-form>

    <view class="btn-box">
      <u-button type="primary" shape="square" :ripple="true" size="medium" @click="toBackPath" class="custom-btn"
        >上一步</u-button
      >
      <u-button type="primary" shape="square" :ripple="true" size="medium" @click="submit" class="custom-btn"
        >提交</u-button
      >
    </view>
    <u-modal
      v-model="showModel"
      content="确认提交数据？"
      @confirm="submitData"
      @cancel="cancel"
      show-cancel-button
    ></u-modal>
    <u-popup v-model="showPopup" mode="bottom" border-radius="10" length="auto" closeable>
      <view class="popup-box">
        <view v-if="showName == 'idCardBadgeImages'">
          <text>1. 必须看清证件信息，且证件信息不能被遮挡;</text>
          <text>2. 您提供的照片信息我们将予以保护，不会用于其它用途;</text>
        </view>
        <view v-else-if="showName == 'backupBankCardNo'">
          <text>1. 必须看清银行卡信息，且银行卡信息不能被遮挡;</text>
          <text>2. 您提供的照片信息我们将予以保护，不会用于其它用途;</text>
        </view>
        <view v-else-if="showName == 'holdIdCardImages'">
          <view class="image"></view>
          <text>1. 请拍摄本人手持身份证正面头部照片和上半身照片;</text>
          <text>2. 照片为免冠、未化妆的数码照片原始图片请勿用任何软件编辑修改;</text>
          <text>3. 必须看清证件信息，且证件信息不能被遮挡，持证人五官清晰可见</text>
          <text>4. 您提供的照片信息易信支付将予以保护，不会用于其它用途</text>
        </view>
      </view>
    </u-popup>
    <u-select
      v-model="actionNameShow"
      :list="actionNameList"
      mode="single-column"
      @confirm="actionNameCallback"
    ></u-select>
  </view>
</template>

<script>
import axios from "axios";
import * as consts from "@/utils/constant.js";
import AuthInfo from "@/utils/authInfo.js";
import { mapGetters } from "vuex";
import { compressImg } from '@/utils/compressor/compress.js'
import {isEmpty} from "../../utils";
import store from "@/store";

export default {
  data() {
    return {
      form: {
        idCardBadgeImages: "", //身份证人像面
        idCardPortraitImages: "", //身份证国徽面
        holdIdCardImages: "", //手持身份证照片
        backupBankCardNo: "", //备用工资卡
        studentCertificate: "", //学生证明材料
        idCardScanning: "", //身份证扫描件
        idCardScanningBak: "", //身份证扫描件备用选项
        bank_shop: "", //开户支行
        bank_cardno: "", //银行卡号
        bank_name: "", //开户银行
        remark1:"",
        remark2:"",
        remark3:""
      },
      rules: {
        bank_name: [
          {
            required: true,
            message: "请选择工资卡开户银行",
            trigger: ["change", "blur"],
          },
        ],
        bank_cardno: [
          {
            required: true,
            message: "请输入工资卡开户银行卡号",
            trigger: ["change", "blur"],
          },
        ],
        bank_shop: [
          {
            required: true,
            message: "请输入工资卡开户行支行",
            trigger: ["change", "blur"],
          },
        ],
        idCardBadgeImages: [
          {
            required: true,
            message: "请上传身份证（人像面）",
            trigger: ["change"],
          },
        ],
        idCardPortraitImages: [
          {
            required: true,
            message: "请上传身份证（国徽面）",
            trigger: ["change"],
          },
        ],
        holdIdCardImages: [
          {
            required: true,
            message: "请上传手持身份证照",
            trigger: ["change"],
          },
        ],
        backupBankCardNo: [
          {
            required: true,
            message: "请上传工资银行卡照片（正面）",
            trigger: ["change"],
          },
        ],
        studentCertificate: [
          {
            required: true,
            message: "请上传学生证明材料",
            trigger: ["change"],
          },
        ],
        // idCardScanning: [
        //   {
        //     required: true,
        //     message: "请上传身份证扫描件",
        //     trigger: ["change"],
        //   },
        // ],
        // idCardScanningBak: [
        //   {
        //     required: true,
        //     message: "请上传身份证扫描件备用选项",
        //     trigger: ["change"],
        //   },
        // ],
      },
      actionNameShow: false,
      actionNameList: [],
      checkBankName: {},
      labelPosition: "top",
      showModel: false,
      showPopup: false,
      showName: "",
      vaildCard: false,
      reqIsStudent: false,
      idCardBadgeImagesFileList:[],
      idCardPortraitImagesFileList:[]
    };
  },
  computed: {
    ...mapGetters(["userInfo","stepType", "qrCodeId"]),
  },
  async mounted() {
    this.userInfo.bankBranch != "" && (this.form.bank_shop = this.userInfo.bankBranch);
    this.userInfo.bankNames &&
      this.userInfo.bankNames.length > 0 &&
      this.userInfo.bankNames.forEach((item) => {
        this.actionNameList.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
    if(this.userInfo.isStudent == 0){
        this.reqIsStudent=true;
    }
    if (this.userInfo.bankName != "") {
      this.userInfo.bankNames &&
        this.userInfo.bankNames.length > 0 &&
        this.userInfo.bankNames.forEach((item) => {
          if (item.dictValue == this.userInfo.bankName) {
            this.form.bank_name = item.dictLabel;
            this.checkBankName = {
              value: item.dictValue,
              label: item.dictLabel,
            };
          }
        });
    }
    //   this.userInfo.idCardBadgeImages != "" && (this.form.idCardBadgeImages = this.userInfo.idCardBadgeImages);
    //   this.userInfo.idCardPortraitImages != "" && (this.form.idCardPortraitImages = this.userInfo.idCardPortraitImages);
    //   this.userInfo.holdIdCardImages != "" && (this.form.holdIdCardImages = this.userInfo.holdIdCardImages);
    //   this.userInfo.backupBankCardNo != "" && (this.form.backupBankCardNo = this.userInfo.backupBankCardNo);
    //   this.userInfo.studentCertificate != "" && (this.form.studentCertificate = this.userInfo.studentCertificate);
    //   this.userInfo.idCardScanning != "" && (this.form.idCardScanning = this.userInfo.idCardScanning);
    //   this.userInfo.idCardScanningBak != "" && (this.form.idCardScanningBak = this.userInfo.idCardScanningBak);
    // let abutmentVo = store.getters.abutmentVo ? store.getters.abutmentVo : []
    const abutmentVo = uni.getStorageSync("abutmentVo")
    this.abutmentVo = abutmentVo
    console.log('abutmentVo====>>',abutmentVo)
    if (!isEmpty(abutmentVo) && !isEmpty(abutmentVo[0])) {
      const file1 = await this.urlToFile('https://dz.yesmac.cn'+ abutmentVo[0].frontimg, 'frontimg.png');
      // this.uploadPic(lists[0].file, "idCardBadgeImages");
      console.log('file1===>>>',file1)
      compressImg({file: file1, success: (result) => {
          this.uploadPic(result, "idCardBadgeImages")
          this.idCardBadgeImagesFileList.push({url:'https://dz.yesmac.cn'+ abutmentVo[0].frontimg})

        }})
      const file2 = await this.urlToFile('https://dz.yesmac.cn'+ abutmentVo[0].backimg, 'backimg.png');
      compressImg({file: file2, success: (result) => {
          this.uploadPic(result, "idCardPortraitImages")
          this.idCardPortraitImagesFileList.push({url:'https://dz.yesmac.cn'+ abutmentVo[0].backimg})
        }})
    }
  },
  methods: {
    async urlToFile(url, filename) {
      const response = await fetch(url);
      const blob = await response.blob();
      return new File([blob], filename, { type: blob.type });
    },
    actionNameCallback(e) {
      this.form.bank_name = e[0].label;
      this.checkBankName = e[0];
    },
    vailCard() {
      this.$u
        .get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json", {
          cardNo: this.form.bank_cardno,
          cardBinCheck: true,
        })
        .then((res) => {
          if (!res.validated) {
            uni.showToast({
              icon: "none",
              title: "请输入正确的银行卡号",
            });
          } else {
            this.vaildCard = true;
          }
        });
    },
    onChangePopup(name) {
      this.showPopup = true;
      this.showName = name;
    },
    toBackPath() {
      this.$u.route("pages/step_one/index");
    },
    idCardBadgeImagesCallback(lists) {
      // this.uploadPic(lists[0].file, "idCardBadgeImages");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "idCardBadgeImages")
      }})
    },
    idCardPortraitImagesCallback(lists) {
      // this.uploadPic(lists[0].file, "idCardPortraitImages");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "idCardPortraitImages")
      }})
    },
    holdIdCardImagesCallback(lists) {
      // this.uploadPic(lists[0].file, "holdIdCardImages");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "holdIdCardImages")
      }})
    },
    backupBankCardNoCallback(lists) {
      // this.uploadPic(lists[0].file, "backupBankCardNo");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "backupBankCardNo")
      }})
    },
    studentCertificateCallback(lists) {
      // this.uploadPic(lists[0].file, "studentCertificate");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "studentCertificate")
      }})
    },
    idCardScanningCallback(lists) {
      // this.uploadPic(lists[0].file, "idCardScanning");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "idCardScanning")
      }})
    },
    idCardScanningBakCallback(lists) {
      // this.uploadPic(lists[0].file, "idCardScanningBak");
      compressImg({file: lists[0].file, success: (result) => {
          this.uploadPic(result, "idCardScanningBak")
      }})
    },
    uploadPic(file, name) {
      const service = axios.create({
        baseURL: consts.API_BASE_URL,
        timeout: 1000 * 60 * 3,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      service.interceptors.request.use(
        (config) => {
          if (
            config.url.indexOf("withoutLogin") == -1 ||
            config.url.indexOf("bindAndLogin") == -1 ||
            config.url.indexOf("listDept") == -1
          ) {
            let token = uni.getStorageSync("token");
            token && token !== "" && (config.headers.Authorization = "Bearer " + token);
          }
          return config;
        },
        (error) => {
          return Promise.reject(error);
        }
      );

      const formData = new FormData();
      formData.append("file", file);

      uni.showLoading({
        title: "图片上传中，请稍后···",
      });

      service({
        url: "/xsdcrm-wechat-api/common/upload",
        method: "POST",
        data: formData,
      }).then((respon) => {
        let res = respon.data;
        uni.hideLoading();
        if (res.code != 200) {
          uni.showToast({
            title: res.msg,
            icon: "error",
          });
          return;
        }
        // this.$set(this.form, name, (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + res.fileName);
        this.$set(this.form, name, res.fileName);
      }).catch((err) => {
        uni.hideLoading();
        uni.showToast({
          title: err,
          icon: "error",
        });
      });
    },
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.showModel = true;
        } else {
          uni.showToast({
            icon: "none",
            title: "验证失败",
          });
        }
      });
    },
    submitData() {
      this.submitInfo();

      // this.$u.route("pages/agree/index");
    },
    cancel() {
      this.showModel = false;
    },
    async submitInfo() {
      let {
        idCardBadgeImages,
        idCardPortraitImages,
        holdIdCardImages,
        backupBankCardNo,
        studentCertificate,
        remark1,
        remark2,
        remark3
        // bank_shop,
        // bank_cardno,
        // idCardScanning,
        // idCardScanningBak,
      } = this.form;
      let params = {
        step: "00",
        idCardBadgeImages,
        idCardPortraitImages,
        holdIdCardImages,
        backupBankCardNo,
        studentCertificate,
        remark1,
        remark2,
        remark3,
        qrcodeId: this.qrCodeId
        // bankBranch: bank_shop,
        // bankName: this.checkBankName.value || "",
        // bankCardNo: bank_cardno,
        // idCardScanning,
        // idCardScanningBak,
      };
      let res = await this.$api.riders.inductionRecord(params);
      if (res.code != 200) {
        uni.showToast({
          title: res.msg,
          icon: "error",
        });
        return;
      }
      uni.showToast({
        title: "数据已提交",
        icon: "success",
      });
      AuthInfo.checkUserStatus();
    },
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.form-box {
  padding: 20px;
}
.custom-btn {
  margin-top: 15px;
  // margin: 15px auto;
  // left: 50%;
  // transform: translateX(-50%);
}
.btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tips {
  display: block;
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}
.to-popup {
  display: block;
  font-size: 12px;
  color: #409eff;
  margin-top: 8px;
}
.popup-box {
  padding: 30px 20px;
  font-size: 14px;
  uni-text {
    display: block;
    margin-top: 8px;
  }
  .image {
    width: calc(280px);
    height: calc(200px);
    margin: auto;
    background-image: url("../../common/imgs/example.png");
    background-repeat: no-repeat;
    background-size: cover;
  }
}
</style>
